package com.zang.concurrent.locks;

import java.util.concurrent.CountDownLatch;

/**
 *
 * synchronized
 *
 * @author Zhang Qiang
 * @Date 2019/9/9 16:11
 */
public class ThreadSafeSample {
    public int  number;
    private static int x = 0, y = 0;
    private static int a = 0, b =0;

    public synchronized void synchronizedAdd() {
        System.out.println("number " + number);
        for (int i = 0; i < 100000; i++) {
            int former = number++;
            int latter = number;
            if (former != latter-1){
                System.out.printf("非相等 former=" +  former + " latter=" + latter);
            }
        }
    }
    public void add() {
        System.out.println("number " + number);
        for (int i = 0; i < 100000; i++) {
            int former = number++;
            int latter = number;
            if (former != latter-1){
                System.out.printf("非相等 former=" +  former + " latter=" + latter);
            }
        }
    }

    public static void testAdd() throws InterruptedException{
        ThreadSafeSample threadSafeSample = new ThreadSafeSample();
        Thread threadA = new Thread(new Runnable() {
            @Override
            public void run() {
                threadSafeSample.add();
            }
        });
        Thread threadB = new Thread(new Runnable() {
            @Override
            public void run() {
                threadSafeSample.add();
            }
        });
        threadA.start();
        threadB.start();
        threadA.join();
        threadB.join();
    }

    public static void main(String[] args) throws InterruptedException {
        testAdd();
//        test();
    }

    public static void test() throws InterruptedException {
        int i = 0;
        for(;;) {
            i++;
            x = 0; y = 0;
            a = 0; b = 0;
            CountDownLatch latch = new CountDownLatch(1);

            Thread one = new Thread(() -> {
                try {
                    latch.await();
                } catch (InterruptedException e) {
                }
                a = 1;
                x = b;
            });

            Thread other = new Thread(() -> {
                try {
                    latch.await();
                } catch (InterruptedException e) {
                }
                b = 1;
                y = a;
            });
            one.start();other.start();
            latch.countDown();
            one.join();other.join();

            String result = "第" + i + "次 (" + x + "," + y + "）";
            if(x == 0 && y == 0) {
                System.err.println(result);
                break;
            } else {
                System.out.println(result);
            }
        }
    }












}
